package com.weiaibenpao.demo.chislim.utils;

import android.os.Handler;
import android.os.Looper;

import com.orhanobut.logger.Logger;


/**
 * Created by Administrator on 2017/12/22.
 * 之所以没使用Android 官方的CountdownTimer是因为它的最后一秒并不会回调，
 * 只会回调到倒数第二秒，然后两秒后直接onFinish()
 */

public class Countdown {
    private Handler handler = new Handler(Looper.getMainLooper());
    private boolean isStop = false;
    private boolean isStarted = false;
    private int countdownSeconds;

    public Countdown(int countdownSeconds) {
        this.countdownSeconds = countdownSeconds;
    }

    public void setOnCountdownListener(OnCountdownListener listener){
        this.onCountdownListener = listener;
    }

    public void stopCountdown() {
        if(isStarted){
            isStop = true;
            handler.removeCallbacksAndMessages(null);
        }
    }

    public void reset(){
        isStarted = false;
        isStop = false;
    }

    public void startCountdown() {
        if (!isStarted) {
            isStarted = true;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = countdownSeconds; i >= 0; i--) {
                        if (isStop) break;
                        Logger.e("countdown--onTick--"+i);
                        if (onCountdownListener != null) {
                            final int leftSeconds = i;
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    onCountdownListener.onTick(leftSeconds);
                                }
                            });
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }

    private OnCountdownListener onCountdownListener;

    public interface OnCountdownListener {
        void onTick(int secondsUntilFinished);
    }
}
